package hook

import (
	"jtdevice/configs"
	"jtdevice/pkg/mqt"
	"strings"

	"github.com/bytedance/sonic"
)

type sender struct {
	mqcli *mqt.Client // TODO多mq推送
}

var (
	Sender sender
)

func (o *sender) Run() (err error) {
	if err = configs.GViper.UnmarshalKey("hook", &opt); err != nil {
		return nil
	}
	if strings.Contains(opt.Address, "nats://") {
		o.mqcli, err = mqt.News("nats", &mqt.Options{Address: opt.Address}, 4)
	}
	return
}

func Publish(topic string, v interface{}) error {
	b, err := sonic.Marshal(v)
	if err != nil {
		return err
	}
	Receiver.handleMsg(topic, b)
	if Sender.mqcli == nil {
		return nil
	}
	return Sender.mqcli.Publish(topic, b)
}

func (o *sender) Release() {
	if o.mqcli != nil {
		o.mqcli.Release()
	}
}
